###################################################################################

library(data.table)
library(optparse)
library(dplyr)
library(ggplot2)
library(ggsci)
library(RColorBrewer)
library(ggpubr)
library(patchwork)

###################################################################################

option_list <- list(
    make_option(c("--input_file"), type = "character") ,
    make_option(c("--mutshare_file"), type = "character") ,
    make_option(c("--mutshare_msi_file"), type = "character") ,
    make_option(c("--images_path"), type = "character")
)

if(1!=1){
    
    input_file <- "~/20220915_gastric_multiple/dna_combinePublic/baseTable/STAD_Info.addBurden.MSI_MSS.addCNVType.tsv"
    mutshare_file <- "~/20220915_gastric_multiple/dna_combinePublic/images/mutRate/MutShare.AllPoint.tsv"
    mutshare_msi_file <- "~/20220915_gastric_multiple/dna_combinePublic/images/mutRateMSI/MutShare.AllPoint.tsv"
    images_path <-"~/20220915_gastric_multiple/dna_combinePublic/images/mutBurden"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

input_file <- opt$input_file
mutshare_msi_file <- opt$mutshare_msi_file
mutshare_file <- opt$mutshare_file
images_path <- opt$images_path

dir.create(images_path , recursive = T)

##############################################################################

col <- c(
  brewer.pal(9,"YlGnBu")[6],
  rgb(234,106,79,alpha=255,maxColorValue=255),
  rgb(203,24,30,alpha=255,maxColorValue=255),
  rgb(255,0,0,alpha=255,maxColorValue=255)
  )

names(col) <- c("IM" , "IGC" , "DGC" , "GC")

##############################################################################

info <- data.frame(fread(input_file))
dat_share <- data.frame(fread(mutshare_file))
dat_share_msi <- data.frame(fread(mutshare_msi_file))

##############################################################################
## 计算每个share的比例
dat_share_rate <- c()
for( sample in unique(dat_share$Tumor) ){
    tmp <- subset( dat_share , Tumor == sample )
    share_nums <- length(which(tmp$Share=="TRUE"))
    private_nums <- length(which(tmp$Share=="FALSE"))
        
    share_rate <- share_nums/(share_nums + private_nums)
    private_rate <- private_nums/(share_nums + private_nums)

    dat_tmp <- data.frame( Tumor = sample , share_nums = share_nums , private_nums = private_nums , 
        share_rate = share_rate , private_rate = private_rate )

    dat_share_rate <- rbind( dat_share_rate , dat_tmp )
}

## MSI
for( sample in unique(dat_share_msi$Tumor) ){
    tmp <- subset( dat_share_msi , Tumor == sample )
    share_nums <- length(which(tmp$Share=="TRUE"))
    private_nums <- length(which(tmp$Share=="FALSE"))
        
    share_rate <- share_nums/(share_nums + private_nums)
    private_rate <- private_nums/(share_nums + private_nums)

    dat_tmp <- data.frame( Tumor = sample , share_nums = share_nums , private_nums = private_nums , 
        share_rate = share_rate , private_rate = private_rate )

    dat_share_rate <- rbind( dat_share_rate , dat_tmp )
}

##############################################################################

dat <- merge( info , dat_share_rate , by = "Tumor" )

##############################################################################

msi_sample <- unique(subset( dat , TCGA_Class %in% c("POLE" , "MSI") )$Patient)
gs_sample <- unique(subset( dat , TCGA_Class %in% c("GS") )$Patient)
cin_sample <- unique(subset( dat , TCGA_Class %in% c("CIN") )$Patient)

##############################################################################
## 分不同亚型
dat <- subset( dat , Class!="IGC + DGC" )

##############################################################################

dat_use <- subset( dat , TCGA_Class == "IM" )
dat_use$Molecular <- ifelse( dat_use$Patient %in% msi_sample , "MSI" , "" )
dat_use$Molecular <- ifelse( dat_use$Patient %in% gs_sample , "GS" , dat_use$Molecular )
dat_use$Molecular <- ifelse( dat_use$Patient %in% cin_sample , "CIN" , dat_use$Molecular )

##############################################################################

trans <- function(num){
    up <- floor(log10(num))
    down <- round(num*10^(-up),2)
    text <- paste("p == ",down," %*% 10","^",up)
    return(text)
}

###########################################################################################

plotBurden <- function(dat_plot_tmp = dat_plot_tmp , type = type , share_class = share_class ){

    dat_plot_tmp$title <- type
    dat_plot_tmp$TCGA_Class <- ifelse( dat_plot_tmp$Patient %in% msi_sample , "MSI" , dat_plot_tmp$TCGA_Class)
    dat_plot_tmp$TCGA_Class <- ifelse( dat_plot_tmp$Patient %in% gs_sample , "GS" , dat_plot_tmp$TCGA_Class)
    dat_plot_tmp$TCGA_Class <- ifelse( dat_plot_tmp$Patient %in% cin_sample , "CIN" , dat_plot_tmp$TCGA_Class)
    dat_plot_tmp$TCGA_Class <- factor( dat_plot_tmp$TCGA_Class , levels = c("MSI" , "CIN" , "GS") , order = T )

    sample_num <- dat_plot_tmp %>%
    group_by( TCGA_Class ) %>%
    summarize( nums = length(unique(Patient)) )

    dat_plot_tmp <- merge( dat_plot_tmp , sample_num , by = "TCGA_Class" )
    dat_plot_tmp$TCGA_Class_num <- paste0(dat_plot_tmp$TCGA_Class , "\n" , "(" , dat_plot_tmp$nums , ")" )

    ## 一个人样本取中位数
    dat_plot_tmp_use <- dat_plot_tmp %>%
    group_by( TCGA_Class_num , Patient , title , TCGA_Class ) %>%
    summarize( share_rate = median(share_rate) , private_rate = median(private_rate) )


    if(share_class == "Share"){
        dat_plot_tmp_use$useCol <- dat_plot_tmp_use$share_rate
        ylab <- "Share Mutation Rate"
    }else if(share_class == "Private"){
        dat_plot_tmp_use$useCol <- dat_plot_tmp_use$private_rate
        ylab <- "Private Mutation Rate"
    }

    my_comparisons_1 <- list( c(1,2) , c(1,3) , c(2,3))

    plot <- ggplot( dat_plot_tmp_use , aes( x = TCGA_Class_num , y = useCol , color = TCGA_Class ) ) +
        geom_line( aes( group = Patient ) , size = 0.4 , color = "gray" ) +  ## 配对样本加线
        geom_boxplot(alpha =1 , size = 0.9 , width = 0.6 , outlier.shape = NA) +
        geom_jitter(position = position_jitter(0.2) , size = 1 , alpha = 0.7) +
        scale_color_npg() +
        facet_grid(.~title) +
        xlab(NULL) +
        ylab(ylab)+
        theme_bw() +
        stat_compare_means(comparisons = my_comparisons_1,method = "wilcox.test") +
        theme(panel.background = element_blank(),#设置背影为白色#清除网格线
            legend.position ='none',
            legend.title = element_blank() ,
            panel.grid.major=element_line(colour=NA),
            plot.title = element_text(size = 8,color="black",face='bold'),
            legend.text = element_text(size = 10,color="black",face='bold'),
            axis.text.y = element_text(size = 10,color="black",face='bold'),
            axis.title.x = element_text(size = 10,color="black",face='bold'),
            axis.title.y = element_text(size = 10,color="black",face='bold'),
            axis.ticks.x = element_blank(),
            axis.text.x = element_text(size = 10,color="black",face='bold') ,
            axis.line = element_line(size = 0.5)) 

    return(plot)
}

##############################################################################
## 分IM+IGC、IM+DGC分别比较
for(share_class in c("Share" , "Private")){
    type <- "All"
    dat_plot_tmp <- data.frame(dat_use)
    dat_plot_tmp <- subset( dat_plot_tmp , Class =="IM" & Type != "IM + IGC + DGC")
    p1 <- plotBurden(dat_plot_tmp = dat_plot_tmp , type = type , share_class )

    type <- "IM + IGC"
    dat_plot_tmp <- data.frame(dat_use)
    dat_plot_tmp <- subset( dat_plot_tmp , Class =="IM" & Type == "IM + IGC")
    p2 <- plotBurden(dat_plot_tmp = dat_plot_tmp , type = type , share_class )

    type <- "IM + DGC"
    dat_plot_tmp <- data.frame(dat_use)
    dat_plot_tmp <- subset( dat_plot_tmp , Class =="IM" & Type == "IM + DGC")
    p3 <- plotBurden(dat_plot_tmp = dat_plot_tmp , type = type , share_class )

    plot <- p1 + p2 + p3

    out_name <- paste0( images_path , "/mutBurden.IM.TCGA_Type.GS_CIN_MSI.MutShareRate.",share_class,".pdf" )  
    ggsave(file=out_name,plot=plot,width=8,height=5)
}